package com.zhihuichongcheng.application.ui.im.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMGroupManager;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.exceptions.HyphenateException;
import com.smartlib.cmnObject.recycleView.OnItemOnclick;
import com.smartlib.cmnObject.util.StringUtil;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.DepInfo;
import com.zhihuichongcheng.application.bean.mine.GroupContactBean;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.im.Constant;
import com.zhihuichongcheng.application.ui.im.adapter.ContactAllAdapter;
import com.zhihuichongcheng.application.ui.im.adapter.ExpListAdapter;
import com.zhihuichongcheng.application.ui.im.adapter.GroupSelectAdapter;
import com.zhihuichongcheng.application.widget.CustomExpandableListView;

import java.util.ArrayList;
import java.util.List;

/**
 * UserListActivity Created by 3water on 2016/10/27.
 */
public class UserListActivity extends BaseActivity implements View.OnClickListener {
    public static final String EXTRA_FOR_RESULT = "extra_for_result";
    public static final String EXTRA_RESULT_USERS = "extra_result_users";
    protected List<EaseUser> contactList = new ArrayList<>();
    protected ImageButton clearSearch;
    private RecyclerView mRcvSelectGroup, mRcvSearch;
    private LinearLayout mRlContact;
    private String[] allMembers;
    private CustomExpandableListView mElvContact;
    private GroupSelectAdapter mAdapter = null;
    private List<UserBean> mSelectData = new ArrayList<>();
    private EditText query = null;
    private UserBean mUser;
    private String groupName = "";
    private ContactAllAdapter mContactAllAdapter;
    private List<UserBean> mFriends = new ArrayList<>();
    private ExpListAdapter adapter;
    private TextView mTvPleaseChoose;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    private String title = "发起群聊";
    private boolean forResult = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (null != getIntent() && null != getIntent().getExtras()) {
            Bundle bundle = getIntent().getExtras();
            if (bundle.containsKey(EXTRA_FOR_RESULT)) {
                forResult = bundle.getBoolean(EXTRA_FOR_RESULT);
            }
        }
        setContentView(R.layout.activity_group);
        initView();
        initData();
    }

    private void initView() {
        mTvPleaseChoose = (TextView) findViewById(R.id.tv_please_choose);
        mRcvSearch = (RecyclerView) findViewById(R.id.rcv_search);
        mRcvSearch.setLayoutManager(new LinearLayoutManager(mContext));
        mContactAllAdapter = new ContactAllAdapter(mContext);
        mRcvSearch.setAdapter(mContactAllAdapter);
        mRlContact = (LinearLayout) findViewById(R.id.rl_contact);
        if (StringUtil.isEmpty(super.title))
            setTitle(title);
        setRightTvUnClick("确定");
        mElvContact = (CustomExpandableListView) findViewById(R.id.elv_contact);
        mRcvSelectGroup = (RecyclerView) findViewById(R.id.rcv_select_group);
        mAdapter = new GroupSelectAdapter(mContext);
        LinearLayoutManager manager = new LinearLayoutManager(mContext);
        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRcvSelectGroup.setLayoutManager(manager);
        mRcvSelectGroup.setAdapter(mAdapter);
        query = (EditText) findViewById(R.id.query);
        clearSearch = (ImageButton) findViewById(R.id.search_clear);
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideKeyboard(query);
            }
        });
        query.setCursorVisible(false);
        query.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                query.setCursorVisible(true);
                return false;
            }
        });
        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    List<UserBean> list = filter(s.toString());
                    if (list.size() > 0) {
                        mRlContact.setVisibility(View.GONE);
                        mContactAllAdapter.setData(list);
                        mContactAllAdapter.setSelsetData(mSelectData);
                        mContactAllAdapter.notifyDataSetChanged();
                        mRcvSearch.setVisibility(View.VISIBLE);
                    }
                } else {
                    mRcvSearch.setVisibility(View.GONE);
                    mRlContact.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        mContactAllAdapter.setOnclick(new OnItemOnclick<UserBean>() {
            @Override
            public void onClick(UserBean userBean, int position) {
                mRcvSearch.setVisibility(View.GONE);
                mRlContact.setVisibility(View.VISIBLE);
                adapter.setSelectUser(userBean);
                adapter.notifyDataSetChanged();
                addSelectData(userBean);
                query.setText("");
            }
        });
    }

    private void initData() {
        mUser = app.getUser();
        mFriends = mUser.getFriends();
        loadData(mFriends);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_ok:
                String desc = "test";
                String reason = "Invite to join the group";
                reason = EMClient.getInstance().getCurrentUser() + reason + groupName;
                EMGroupManager.EMGroupOptions option = new EMGroupManager.EMGroupOptions();
                option.maxUsers = 200;
                option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin;
                try {
                    final EMGroup emGroup = EMClient.getInstance().groupManager().createGroup(groupName, desc, allMembers, reason, option);
                    Bundle bundle = new Bundle();
                    bundle.putInt(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
                    bundle.putString("userId", emGroup.getGroupId());
                    startActivity(ChatActivity.class, bundle);
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    /***
     *
     */

    public List<UserBean> filter(String str) {
        List<UserBean> easeUsers = new ArrayList<>();
        for (int i = 0; i < mFriends.size(); i++) {
            UserBean easeUser = mFriends.get(i);
            if (easeUser.getUserName().contains(str)) {
                easeUsers.add(easeUser);
            }
        }

        return easeUsers;
    }

    private void loadData(List<UserBean> list) {
        final List<String> groups = new ArrayList<>();
        List<List<GroupContactBean>> childs = new ArrayList<>();
        List<GroupContactBean> childItem = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            final UserBean easeUser = list.get(i);
            final DepInfo info = easeUser.getDept();
            if (info != null) {
                DepInfo preInfo = null;
                if (i > 0) {
                    preInfo = list.get(i - 1).getDept();
                }
                String preHead = "";
                if (preInfo != null) {
                    preHead = preInfo.getDeptName();
                }
                String header = info.getDeptName();
                if (i == 0 || TextUtils.isEmpty(preHead) || header != null && !header.equals(preHead)) {
                    if (!TextUtils.isEmpty(header)) {
                        groups.add(header);
                        if (i > 0) {
                            childs.add(childItem);
                        }
                        childItem = new ArrayList<>();
                    }
                }
                final GroupContactBean bean = new GroupContactBean();
                bean.setBean(easeUser);
                bean.setSelect(false);
                childItem.add(bean);
            }
        }
        childs.add(childItem);
        adapter = new ExpListAdapter(mContext, groups, childs);
        adapter.setShowChildNum(false);
        mElvContact.setAdapter(adapter);
        mElvContact.setGroupIndicator(null);
        mElvContact.expandGroup(0);
        adapter.setOnItemClick(new OnItemOnclick<UserBean>() {
            @Override
            public void onClick(UserBean userBean, int position) {
                addSelectData(userBean);
            }
        });
    }


    private void addSelectData(UserBean userBean) {
        if (!mSelectData.contains(userBean)) {
            mSelectData.add(userBean);
        } else {
            mSelectData.remove(userBean);
        }
        if (mSelectData.size() > 0) {
            mTvPleaseChoose.setVisibility(View.GONE);
            mRcvSelectGroup.setVisibility(View.VISIBLE);
            setTvRight("确定(" + mSelectData.size() + ")", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (forResult)
                        toResult();
                    else
                        startGroupChat();
                }
            });
        } else {
            mRcvSelectGroup.setVisibility(View.GONE);
            mTvPleaseChoose.setVisibility(View.VISIBLE);
            setRightTvUnClick("确定");
        }
        mAdapter.setData(mSelectData);
        mAdapter.notifyDataSetChanged();
    }

    private void toResult() {
        Intent intent = new Intent();
        intent.putParcelableArrayListExtra(EXTRA_RESULT_USERS, (ArrayList<? extends Parcelable>) mSelectData);
        setResult(EXTRA_RESPONSE_CODE_SUCCESS, intent);
        finish();
    }

    private void startGroupChat() {
        allMembers = new String[mSelectData.size()];
        for (int j = 0; j < mSelectData.size(); j++) {
            UserBean selectBean = mSelectData.get(j);
            allMembers[j] = selectBean.getEasemobNumber();
            if (j < 2) {
                groupName = groupName + selectBean.getUserName() + ",";
            }
        }
        if (mSelectData.size() > 2) {
            groupName = groupName + mUser.getUserName();
        } else {
            groupName = groupName + mUser.getUserName();
        }
        addGroup(groupName, allMembers);
    }

    private void addGroup(String groupName, String[] allMembers) {
        String desc = "test";
        String reason = "Invite to join the group";
        reason = EMClient.getInstance().getCurrentUser() + reason + groupName;
        EMGroupManager.EMGroupOptions option = new EMGroupManager.EMGroupOptions();
        option.maxUsers = 200;
        option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin;
        try {
            final EMGroup emGroup = EMClient.getInstance().groupManager().createGroup(groupName, desc, allMembers, reason, option);
            Bundle bundle = new Bundle();
            bundle.putInt(Constant.EXTRA_CHAT_TYPE, Constant.CHATTYPE_GROUP);
            bundle.putString("userId", emGroup.getGroupId());
            startActivity(ChatActivity.class, bundle);
            finish();
        } catch (HyphenateException e) {
            e.printStackTrace();
        }
    }


}
